package com.xxxy.jsq.action.role;

import com.xxxy.jsq.dao.RoleDao;
import com.xxxy.jsq.model.Role;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/updateRoleServlet")
public class updateRoleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public updateRoleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码，避免中文乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建角色模型和DAO对象
        Role model = new Role();
        RoleDao dao = new RoleDao();

        // 获取页面传递的参数（与前端表单字段名完全对应）
        String roleFlag = request.getParameter("cflag");    // 状态（对应前端name="cflag"）
        String roleName = request.getParameter("cname");    // 角色名称（对应前端name="cname"）
        Long roleId = Long.valueOf(request.getParameter("cid"));  // 角色ID（对应前端隐藏域name="cid"）

        // 设置模型对象属性
        if (roleFlag != null && !roleFlag.equals("")) {
            model.setRoleFlag(roleFlag);
        }
        if (roleName != null && !roleName.equals("")) {
            model.setRoleName(roleName);
        }
        model.setRoleId(roleId);  // 设置角色ID（用于标识更新对象）

        // 调用DAO层的更新方法
        String result = dao.update(model);

        // 将更新结果返回给前端
        PrintWriter out = response.getWriter();
        out.print(result);  // 返回"Ok"表示成功，"Same"表示名称重复，"Err"或异常信息表示失败
        out.flush();
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST请求与GET处理逻辑一致
        doGet(request, response);
    }
}